package com.example.sunran.service.impl;

import com.example.sunran.model.PhoneInfo;
import com.example.sunran.service.PhoneRecognizeService;

import java.io.*;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @program: 小班课1-手机号码识别
 * @description: 手机号码识别实现类
 * @author: SunRan
 * @create: 2018-11-11 11:58
 **/
public class PhoneRecognizeServiceImpl implements PhoneRecognizeService {

    private static Map<String, PhoneInfo> phoneInfoMap = new LinkedHashMap<>();

    @Override
    public PhoneInfo onCall(String phone) {

        String phonePrefix = phone.substring(0, 7);

        return phoneInfoMap.get(phonePrefix);
    }

    @Override
    public  boolean initPhoneInfo() {

        FileInputStream fis = null;

        try {
            fis = new FileInputStream("./phone.data.txt");
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);

            String line = "";
            while ((line = br.readLine()) != null) {

                String[] info = line.split("\t");

                PhoneInfo phoneInfo = new PhoneInfo();

                phoneInfo.setPhone(info[0]);
                phoneInfo.setProvince(info[1]);
                phoneInfo.setCity(info[2]);
                phoneInfo.setOperator(info[3]);
                phoneInfo.setCityCode(info[4]);
                phoneInfo.setPostCode(info[5]);

                phoneInfoMap.put(info[0], phoneInfo);

            }

            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return false;
    }


    public int  binarySearch(int[] arr,int key){

        int start = 0;
        int end = arr.length-1;


        while (start <= end) {

            int middle = (start+end)/2;

            if (arr[middle] == key) {
                return arr[middle];
            }else if(arr[middle] < key){
                start = middle+1;
            }else{
                end = middle-1;
            }
        }

        return -1;
    }
    public static void main(String[] args) {



    }
}
